package com.gejia.qixishare.utils.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;
import com.gejia.qixishare.enums.BaseResponseCode;
import com.gejia.qixishare.exceptions.BusinessException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class AliyunOSSUtils {
    @Autowired
    private OSSConfig ossConfig;

    @Autowired
    private OSS ossClient;
    /**
     * 上传文件
     * *
     @param file
      * @return
     */
    public String fileUpload(MultipartFile file) {
        String fullurl = "";
        try {
            String url = ossConfig.getUrlPrefix();
            System.err.println("OSS url"+ url);
            byte[] b = file.getBytes();
            ByteArrayInputStream in = new ByteArrayInputStream(b);
            String fileName = file.getOriginalFilename();
            String filePath = getFilePath(fileName);
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType("image/jpg");
            ossClient.putObject(ossConfig.getBucketName(), filePath, in,
                    objectMetadata);
//下载的全路径
            fullurl = url + "/" + filePath;
        } catch (Exception e) {
            System.err.println(e.getMessage());
            throw new BusinessException(BaseResponseCode.AliCloud_OSS_FILE_UPLOAD_ERROR);
        }
        return fullurl;
    }

    private String getFilePath(String sourceFileName) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return ossConfig.getBucketName() + "/" + sdf.format(new Date()) + "/"
                + System.currentTimeMillis() +
                RandomUtils.nextInt(9999) + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }
}
